package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class utoFillaspect {
//切入点(对哪些类的哪些方法进行拦截)

    @Pointcut("execution(* com.sky.mapper.*.*(..))&& @annotation(com.sky.annotation.AutoFill)")
    public void Pointcut(){

    }
    @Before("Pointcut()")

    //JoinPoint 参数是连接点的上下文对象，用于获取被拦截方法的核心信息，比如目标方法、参数、所属类等
    public void Autofill(JoinPoint joinPoint){
log.info("公共字段填充");
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();//获得方法签名对象
AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);//获得注解对象
        OperationType operationType = autoFill.value();//获得注解的value，以确定操作数据库的类型

       //获得被拦截方法的参数----实体对象
        Object[] args = joinPoint.getArgs();
        if(args==null || args.length==0){
             return;
        }
        Object object = args[0];
        LocalDateTime now=LocalDateTime.now();
        Long id= BaseContext.getCurrentId();
        if(operationType==OperationType.INSERT){

            try {
                //方法名称，方法参数
                //获得方法

                Method setCreateTime=  object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                Method setCreateuser=  object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method setUpdateTime=  object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setUpdateUser=  object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
         //为对象属性赋值
            setCreateTime.invoke(object,now);
            setCreateuser.invoke(object,id);
            setUpdateTime.invoke(object,now);
            setUpdateUser.invoke(object,id);

            } catch (Exception e) {
               e.printStackTrace();
            }

        }else if(operationType==OperationType.UPDATE){
            try {
                //方法名称，方法参数
                //获得方法


                Method setUpdateTime=  object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setUpdateUser=  object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                //为对象属性赋值

                setUpdateTime.invoke(object,now);
                setUpdateUser.invoke(object,id);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
